#!/bin/bash
###############################################################################
#       脚本名称: benchmark_config.sh
#       功能描述: 配置模块性能基准测试
#       作者: 林再来
#       日期: 2025-10-13
#       版本: 1.0
###############################################################################

cd "$(dirname "${BASH_SOURCE[0]}")" || exit 1

# 加载配置模块
source ../../scripts/config/config.sh

# 创建临时测试目录
TEST_DIR=$(mktemp -d "${TMPDIR:-/tmp}/benchmark_XXXXXX")

# 颜色定义
COLOR_GREEN='\033[0;32m'
COLOR_BLUE='\033[0;34m'
COLOR_YELLOW='\033[1;33m'
COLOR_RESET='\033[0m'

###############################################################################
# 性能测试函数
###############################################################################

# 函数: 测量执行时间
measure_time() {
    local start_time=$(date +%s%N)
    "$@" >/dev/null 2>&1
    local end_time=$(date +%s%N)
    
    # 计算毫秒
    local duration=$(( (end_time - start_time) / 1000000 ))
    echo "$duration"
}

# 函数: 运行基准测试
run_benchmark() {
    local test_name="$1"
    local iterations="${2:-100}"
    shift 2
    
    echo -e "${COLOR_BLUE}基准测试: $test_name${COLOR_RESET}"
    echo "  迭代次数: $iterations"
    
    local total_time=0
    local min_time=999999999
    local max_time=0
    
    for ((i=1; i<=iterations; i++)); do
        local duration=$(measure_time "$@")
        total_time=$((total_time + duration))
        
        if [[ $duration -lt $min_time ]]; then
            min_time=$duration
        fi
        
        if [[ $duration -gt $max_time ]]; then
            max_time=$duration
        fi
    done
    
    local avg_time=$((total_time / iterations))
    
    echo -e "  平均耗时: ${COLOR_GREEN}${avg_time}ms${COLOR_RESET}"
    echo "  最小耗时: ${min_time}ms"
    echo "  最大耗时: ${max_time}ms"
    echo "  总耗时:   ${total_time}ms"
    echo ""
}

###############################################################################
# 基准测试用例
###############################################################################

echo "========================================"
echo "配置模块性能基准测试"
echo "========================================"
echo ""

# 初始化
config_init 2>/dev/null

# 准备测试文件
prepare_test_files() {
    # YAML文件
    cat > "$TEST_DIR/test.yaml" << 'EOF'
app:
  name: BenchmarkApp
  version: 1.0.0
  config:
    timeout: 30
    max_connections: 100
    features:
      - feature1
      - feature2
      - feature3
EOF
    
    # JSON文件
    cat > "$TEST_DIR/test.json" << 'EOF'
{
  "app": {
    "name": "BenchmarkApp",
    "version": "1.0.0",
    "config": {
      "timeout": 30,
      "max_connections": 100,
      "features": ["feature1", "feature2", "feature3"]
    }
  }
}
EOF
    
    # ENV文件
    cat > "$TEST_DIR/test.env" << 'EOF'
APP_NAME=BenchmarkApp
APP_VERSION=1.0.0
TIMEOUT=30
MAX_CONNECTIONS=100
EOF
    
    # INI文件
    cat > "$TEST_DIR/test.ini" << 'EOF'
[app]
name=BenchmarkApp
version=1.0.0

[config]
timeout=30
max_connections=100
EOF
}

prepare_test_files

# 1. 配置加载性能
echo -e "${COLOR_YELLOW}=== 配置加载性能 ===${COLOR_RESET}"
echo ""

run_benchmark "YAML文件加载" 50 config_load "$TEST_DIR/test.yaml" "yaml_bench" true
run_benchmark "JSON文件加载" 50 config_load "$TEST_DIR/test.json" "json_bench" true
run_benchmark "ENV文件加载" 50 config_load "$TEST_DIR/test.env" "env_bench" true
run_benchmark "INI文件加载" 50 config_load "$TEST_DIR/test.ini" "ini_bench" true

# 2. 配置读取性能
echo -e "${COLOR_YELLOW}=== 配置读取性能 ===${COLOR_RESET}"
echo ""

config_load "$TEST_DIR/test.yaml" "yaml_read" 2>/dev/null
config_load "$TEST_DIR/test.json" "json_read" 2>/dev/null
config_load "$TEST_DIR/test.env" "env_read" 2>/dev/null
config_load "$TEST_DIR/test.ini" "ini_read" 2>/dev/null

run_benchmark "YAML值读取" 100 config_get "yaml_read" ".app.name"
run_benchmark "JSON值读取" 100 config_get "json_read" ".app.name"
run_benchmark "ENV值读取" 100 config_get "env_read" "APP_NAME"
run_benchmark "INI值读取" 100 config_get "ini_read" "app.name"

# 3. 配置写入性能
echo -e "${COLOR_YELLOW}=== 配置写入性能 ===${COLOR_RESET}"
echo ""

run_benchmark "YAML值写入" 20 config_set "yaml_read" ".app.test" "value" "string"
run_benchmark "JSON值写入" 20 config_set "json_read" ".app.test" "value" "string"
run_benchmark "ENV值写入" 20 config_set "env_read" "TEST_VAR" "value"
run_benchmark "INI值写入" 20 config_set "ini_read" "app.test" "value"

# 4. 哈希计算性能
echo -e "${COLOR_YELLOW}=== 哈希计算性能 ===${COLOR_RESET}"
echo ""

source ../../scripts/config/yq.sh
source ../../scripts/config/jq.sh
source ../../scripts/config/env.sh
source ../../scripts/config/ini.sh

run_benchmark "YAML哈希计算" 50 yq_get_hash "$TEST_DIR/test.yaml"
run_benchmark "JSON哈希计算" 50 jq_get_hash "$TEST_DIR/test.json"
run_benchmark "ENV哈希计算" 50 env_get_hash "$TEST_DIR/test.env"
run_benchmark "INI哈希计算" 50 ini_get_hash "$TEST_DIR/test.ini"

# 5. 大文件性能测试
echo -e "${COLOR_YELLOW}=== 大文件性能测试 ===${COLOR_RESET}"
echo ""

# 创建大YAML文件
large_yaml="$TEST_DIR/large.yaml"
echo "data:" > "$large_yaml"
for i in {1..100}; do
    echo "  item${i}:" >> "$large_yaml"
    echo "    name: item${i}" >> "$large_yaml"
    echo "    value: ${i}" >> "$large_yaml"
done

run_benchmark "大YAML文件加载(100项)" 10 config_load "$large_yaml" "large_yaml" true
config_load "$large_yaml" "large_yaml" 2>/dev/null
run_benchmark "大YAML文件读取" 50 config_get "large_yaml" ".data.item50.name"

# 6. 批量操作性能
echo -e "${COLOR_YELLOW}=== 批量操作性能 ===${COLOR_RESET}"
echo ""

batch_test() {
    local format="$1"
    local file="$2"
    local id="batch_$format"
    
    config_load "$file" "$id" 2>/dev/null
    for i in {1..10}; do
        if [[ "$format" == "yaml" ]] || [[ "$format" == "json" ]]; then
            config_get "$id" ".app.name" >/dev/null 2>&1
        elif [[ "$format" == "env" ]]; then
            config_get "$id" "APP_NAME" >/dev/null 2>&1
        else
            config_get "$id" "app.name" >/dev/null 2>&1
        fi
    done
}

run_benchmark "YAML批量读取(10次)" 20 batch_test "yaml" "$TEST_DIR/test.yaml"
run_benchmark "JSON批量读取(10次)" 20 batch_test "json" "$TEST_DIR/test.json"
run_benchmark "ENV批量读取(10次)" 20 batch_test "env" "$TEST_DIR/test.env"
run_benchmark "INI批量读取(10次)" 20 batch_test "ini" "$TEST_DIR/test.ini"

# 清理
rm -rf "$TEST_DIR"

echo "========================================"
echo "基准测试完成"
echo "========================================"
echo ""
echo "性能优化建议:"
echo "1. 对于频繁读取的配置，考虑启用缓存"
echo "2. 大文件建议只读取需要的部分，避免全量加载"
echo "3. 批量操作时，合理使用配置重载策略"
echo "4. 选择合适的配置格式：YAML/JSON适合复杂结构，ENV/INI适合简单配置"
echo ""

